package com.pandas.community.controller;

import com.pandas.community.Utils.CommunityConstant;
import com.pandas.community.Utils.CommunityUtil;
import com.pandas.community.Utils.HostHolder;
import com.pandas.community.entity.Event;
import com.pandas.community.entity.User;
import com.pandas.community.event.EventProducer;
import com.pandas.community.service.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class LikeController implements CommunityConstant {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;


    @RequestMapping(value = "/like", method = RequestMethod.POST)
    @ResponseBody
    public String like(int entityType, int entityId, int entityUserid, int postId){
        //报错，用户是否登录在advice统一处理，后面会使用SpringSecurity
        //或者使用拦截器
        User user = hostHolder.getUser();

        //点赞
        likeService.like(user.getId(), entityType, entityId, entityUserid);

        //数量
        long likeCount = likeService.getEntityLikeCount(entityType, entityId);
        //状态
        int likeStatus = likeService.getEntityLikeStatus(user.getId(), entityType, entityId);

        //返回的结果
        Map<String, Object> map = new HashMap<>();

        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);

        //触发点赞事件
        if(likeStatus == 1){
            Event event = new Event()
                    .setTopic(TOPIC_LIKE)
                    .setUserId(user.getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityUserid)
                    .setData("postId", postId);
            eventProducer.fireEvent(event);
        }




        return CommunityUtil.getJSONString(0, null, map);
    }
}
